package com.lagou.balance.impl;

import com.lagou.common.Metrics;
import com.lagou.common.RequestMetrics;
import com.lagou.server.RpcClient;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class MinCostLoadBalance extends AbstractLoadBalanceStrategy{
    @Override
    protected RpcClient doSelect(List<RpcClient> rpcClients) {
        if(CollectionUtils.isEmpty(rpcClients)){
            return null;
        }
        ConcurrentHashMap<String, Long> metricMap = RequestMetrics.getInstance().getMetricMap();

        RpcClient minRpcClient = rpcClients.get(0);
        Long min = metricMap.get(minRpcClient.getNettyIp() + minRpcClient.getPort());

        for (int i = 1; i < rpcClients.size(); i++) {
            RpcClient rpcClient = rpcClients.get(i);

            String nettyIp = rpcClient.getNettyIp();
            int port = rpcClient.getPort();

            Long aLong = metricMap.get(nettyIp + port);
            if(aLong != null && aLong < min){
                minRpcClient = rpcClient;
            }
        }
        return minRpcClient;
    }
}
